<template>
    <el-row :gutter="20">
        <el-col>
            <el-tabs v-model="editableTabsValue" @tab-click="handleClick" type="card" class="demo-tabs" closable
                @tab-remove="removeTab">
                <el-tab-pane v-for="item in editableTabs" :key="item.name" :label="item.title" :name="item.name">
                </el-tab-pane>
            </el-tabs>
        </el-col>
    </el-row>

</template>

<script setup>
import { ref, watch } from 'vue'
import { useTabsStore } from '@/store/tabs/index.js'
import { useRouter } from 'vue-router'

const $router = useRouter()

const editableTabsValue = ref(useTabsStore().editableTabsValue)
const editableTabs = ref(useTabsStore().editableTabs)

const removeTab = (targetName) => {
    const tabs = editableTabs.value
    let activeName = editableTabsValue.value

    if (targetName == '/home') {
        return
    }

    if (activeName === targetName) {
        tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
                const nextTab = tabs[index + 1] || tabs[index - 1]
                if (nextTab) {
                    activeName = nextTab.name
                }
            }
        })
    }

    editableTabsValue.value = activeName
    editableTabs.value = tabs.filter((tab) => tab.name !== targetName)

    useTabsStore().setEditableTabsValue(editableTabsValue.value)
    useTabsStore().setEditableTabs(editableTabs.value)

    $router.push({
        path: editableTabsValue.value,
    }).catch(err => { })
}

const handleClick = (tab, event) => {
    console.log("---", tab.props.name)
    $router.push({
        path: tab.props.name,
    }).catch(err => { })
}


const refreshTabs = () => {
    editableTabsValue.value = useTabsStore().editableTabsValue
    editableTabs.value = useTabsStore().editableTabs
}

watch(useTabsStore(), () => {
    refreshTabs()
}, { deep: true, immediate: true })
</script>

<style lang="scss" scoped>
.demo-tabs {
    // padding: 10px;
    // margin-left: 5px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
}

.el-tab-pane {
    margin-left: 5px;
}

:deep(.el-tabs__header) {
    margin: 0;
}

:deep(.el-tabs__item.is-active) {
    background: lightgray;
}

:deep(.el-tabs__item.is-active) {
    color: #6b778c;
}
</style>
